# 把变量从内存中变成可存储或传输的过程称之为序列化，在Python中叫pickling，
# 在其他语言中也被称之为serialization，marshalling，flattening等等
import pickle
import os
import json
d1 = dict(name="Bill", age=9, score=99)
d2 = dict(name="Bill", age=9, score=55)
pickle.dumps(d1)  # 把任意对象序列化成一个bytes
f1 = open("E:\\Python_Basic\\_09_IO编程\\_01_文件读写.txt", "wb")
pickle.dump(d2, f1)  # 直接把对象序列化后写入一个file-like Object
f1.close()
f2 = open("E:\\Python_Basic\\_09_IO编程\\_01_文件读写.txt", "rb")
f3 = pickle.load(f2)  # 反序列化
f2.close()
print(f3)
# --------------------------JSON--------------JSON编码是UTF-8-------------------
d3 = dict(name="Jack", carer="Teacher", salary=9000)
print(json.dumps(d3))  # 返回一个str，内容就是标准的JSON。
f5 = open("E:\\Python_Basic\\_09_IO编程\\_01_文件读写.txt", "w")
json.dump(d2, f5)
f5.close()
f6 = open("E:\\Python_Basic\\_09_IO编程\\_01_文件读写.txt", "r")
print(json.loads(f6.read()))
f6.close()
# ---------------------------------如何将实例对象JSON化---


class Student(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score


def student2dict(student):
    return {
        "name": student.name,
        "age": student.age,
        "score": student.score
    }


def dict2student(d):
    return Student(d["name"], d["age"], d["score"])


stu = Student("Bob", 11, 90)
print(json.dumps(stu, default=student2dict))
stu_json = '{"name": "Tom", "age": 9, "score": 99}'
print(json.loads(stu_json, object_hook=dict2student))
